package a.a.a.filesystem;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

@Repository
public class ContestRepository {

	@Value("${path.root}")
	private String path;

	@Autowired
	private GroupRepository groupRepository;

	public GroupRepository getGroupRepository() {
		return groupRepository;
	}

	public void setGroupRepository(GroupRepository groupRepository) {
		this.groupRepository = groupRepository;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public boolean contestExists(String group, String name) {
		if (!groupRepository.groupExists(group)) {
			return false;
		}
		File file = new File(path + group + "/" + name);
		return (file.exists() && file.isDirectory());
	}

	public boolean createContest(String group, String name) {
		if (!contestExists(group, name)) {
			File file = new File(path + group + "/" + name);
			return file.mkdir();
		}
		return false;
	}
	
	public List<String> getContests(String group) {
		List<String> contests = new ArrayList<String>();
		for (File f : new File(path + group + "/").listFiles()) {
			if (f.isDirectory()) {
				contests.add(f.getName());
			}
		}
		return contests;
	}
	
	public boolean removeContest(String group, String name) {
		if (contestExists(group, name)) {
			File file = new File(path + group + "/" + name);
			return file.delete();
		}
		return false;
	}
}
